<template>
  <div class="i18n">
    <h1>{{ msg || $t('title') }}</h1> <!-- 如果 msg 存在则显示 msg，否则使用 i18n 的 title -->
    <h2>{{ $t('app.welcome') }}</h2>
    <button @click="switchLanguage('zhCN')">简体中文</button>
    <button @click="switchLanguage('zhHK')">繁体中文</button>
    <button @click="switchLanguage('en-US')">English</button>
  </div>
</template>

<script setup>
import { defineProps, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';

const props = defineProps({
  msg: String
});

const { locale, t } = useI18n();



const setLocale = (lang) => {
  locale.value = lang;
  localStorage.setItem('user-locale', lang);
  // document.querySelector('html').setAttribute('lang', lang);
}
const switchLanguage = (lang) => {
  console.log('switchLanguage',lang);
  setLocale(lang);
  locale.value = lang;
};
onMounted(() => {
  // 从 localStorage 中读取用户之前选择的语言
  const savedLocale = localStorage.getItem('user-locale');
  if (savedLocale) {
    setLocale(savedLocale);
  } else {
    // 根据浏览器语言自动选择
    const browserLang = navigator.language || navigator.userLanguage;
    if (browserLang.startsWith('zh')) {
      if (browserLang.includes('HK') || browserLang.includes('TW')) {
        setLocale('zh-HK');
      } else {
        setLocale('zh-CN');
      }
    } else {
      setLocale('en');
    }
  }
});

</script>

<style scoped>
/* 样式内容 */
</style>